#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 3e5 + 5;

int n, m;
int a[N];

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n;
  rep(i, 1, n) cin >> a[i];
  priority_queue<int, vector<int>, greater<int>> left, right;
  /*
   a better solution, merge left and right
   as the element in right heap could be regreted.
   we could treat it as the element in left heap.
   */
  ll sum = 0;
  rep(i, 1, n) {
    int x = right.size() ? right.top() : 1e9;
    int y = left.size() ? left.top() : 1e9;
    int z = min(x, y);
    if (z < a[i]) {
      if (z == x)
        right.pop(), left.push(x);
      else
        left.pop();
      right.push(a[i]);
      sum += a[i] - z;
    } else {
      left.push(a[i]);
    }
  }
  cout << sum;
  return 0;
}